home *** CD-ROM | disk | FTP | other *** search
/ Java Developer's Companion / Java Developer's Companion.iso / Javacup / PR8ADPL7.TAR / productivity_tools / PR8ADPL7 / MultiLabel.java < prev    next >
Encoding:
Java Source  |  1996-05-23  |  1.5 KB  |  79 lines

  1. // MultiLabel.java
  2. // A multi-line label
  3. import java.awt.*;
  4. import java.util.Vector;
  5.  
  6. public class MultiLabel extends Canvas
  7. {
  8.     String message;
  9.     FontMetrics fnm = null;
  10.  
  11.     MultiLabel(String msg)
  12.     {
  13.     message = msg;
  14.     }
  15.  
  16.     // paint
  17.     // Render the text into the space available
  18.     public void paint(Graphics g)
  19.     {
  20.     int w = size().width;
  21.     Vector lines = makelines(g, w);
  22.     g.setColor(Color.black);
  23.     for(int y=0; y<lines.size(); y++) {
  24.         // Draw line
  25.         String line = (String)lines.elementAt(y);
  26.         g.drawString(line,
  27.                  (w-fnm.stringWidth(line))/2,
  28.                  (y+1)*fnm.getHeight());
  29.         }
  30.     }
  31.  
  32.     // makelines
  33.     // Returns a vector of Strings, each less than w pixels
  34.     Vector makelines(Graphics g, int w)
  35.     {
  36.     Vector lines = new Vector();
  37.     if (fnm == null) fnm = g.getFontMetrics();
  38.     String rest = message.trim();
  39.     while(rest.length() != 0) {
  40.         // Get w pixels worth of characters
  41.         int i = rest.length()-1;
  42.         String sub;
  43.         while(fnm.stringWidth(sub = rest.substring(0,i+1)) > w && i > 0)
  44.             i--;
  45.  
  46.         // Break at space if possible
  47.         int spc = sub.lastIndexOf(' ');
  48.         int brk;
  49.         if (spc < 0 || sub.length() == rest.length())
  50.             brk = sub.length();    // cannot or don't need to break
  51.         else
  52.             brk = spc;
  53.  
  54.         // Add line
  55.         lines.addElement(rest.substring(0, brk));
  56.         rest = rest.substring(brk);
  57.         }
  58.     return lines;
  59.     }
  60.  
  61.     public Dimension minimumSize()
  62.     {
  63.     Graphics g = getGraphics();
  64.     if (g == null) {
  65.         return new Dimension(200,120);
  66.         }
  67.     else {
  68.         int lc = makelines(g, 200).size();
  69.         return new Dimension(200, lc*fnm.getHeight());
  70.         }
  71.     }
  72.  
  73.     public Dimension preferredSize()
  74.     {
  75.     return minimumSize();
  76.     }
  77. }
  78.  
  79.